#include "kdcmplayerwindow.h"

#include <kdclib.h>
#include <QVBoxLayout>

KDCMPlayerWindow::KDCMPlayerWindow( QWidget *aParent ) : QWidget( aParent ), pDisplayWindow( NULL )
{
	setAttribute( Qt::WA_PaintOnScreen );
	//setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
	QPalette p = palette();
	p.setColor( QPalette::Window, Qt::black );
	setPalette( p );

	QVBoxLayout *vLayout = new QVBoxLayout( this );
	setDisplayWindow( new QWidget );
}

void KDCMPlayerWindow::setDisplayWindow( QWidget *aWidget )
{
	if ( aWidget )
	{
		QVBoxLayout *vLayout = qobject_cast<QVBoxLayout*>( layout() );
		vLayout->removeWidget( pDisplayWindow );
		deletePtr( pDisplayWindow );
		pDisplayWindow = aWidget;
		pDisplayWindow->setSizePolicy( QSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed ) );
		pDisplayWindow->setAttribute( Qt::WA_PaintOnScreen );
		pDisplayWindow->setParent( this );
		vLayout->addWidget( pDisplayWindow );
	}
}

QWidget* KDCMPlayerWindow::displayWindow() const
{
	return ( pDisplayWindow ) ? pDisplayWindow : const_cast<KDCMPlayerWindow*>( this );
}

void KDCMPlayerWindow::resizeEvent( QResizeEvent *aEvent )
{
	QWidget::resizeEvent( aEvent );
	setMovieProperties( pWidth, pHeight, pAspect );
}

void KDCMPlayerWindow::setWindowSize( int aWidth, int aHeight )
{
	resize( aWidth, aHeight );
	if ( pDisplayWindow )
		pDisplayWindow->resize( aWidth, aHeight );
}

void KDCMPlayerWindow::setMovieProperties( int aWidth, int aHeight, double aAspect )
{
	pWidth = aWidth;
	pHeight = aHeight;
	pAspect = aAspect;

	double scale_w = (double)width() / (double)pWidth;
	int new_height_w = qRound( scale_w * pHeight );
	if ( new_height_w <= height() ) // width
	{
		//int size = qBound( 0, qRound( width()/pAspect ), height() );
		displayWindow()->resize( width(), new_height_w );
		//displayWindow()->setMaximumSize( width(), new_height_w );
		displayWindow()->move( 0, qRound( qAbs( (double)new_height_w - (double)height() ) * 0.5 ) );
	}
	else // height
	{
		int size = qBound( 0, qRound( height()*pAspect ), width() );
		displayWindow()->resize( size, height() );
		//displayWindow()->setMaximumSize( size, height() );
		displayWindow()->move( qRound( qAbs( (double)size - (double)width() ) * 0.5 ), 0 );
	}
}
